<?php
if ( !defined('IN_ADMINCP') || !defined('IN_SEC') ){
	exit('Access Denied.');
}

$acts = array(
	'insert_contact', 'change_field', 'upload_file', 'delete_file'
);
$act = in_array($_G['gp_act'], $acts, true) ? $_G['gp_act'] : '';
$dataid = intval(abs($_G['gp_dataid']));
if ( $act == 'insert_contact' ){
	$type = $_G['gp_type'];
	$content = htmlspecialchars($_G['gp_content']);
	$files = $_G['gp_files'] ? json_encode($_G['gp_files']) : '';

	if( !$type || !$content ){
		jsonp('资料填写不完整', 'alert', 1);
	}

	DB::Insert('customer_contacts', array(
		'adminid' => $admincp->adminid,
		'customerid' => $customer['id'],
		'type' => $type,
		'content' => $content,
		'files' => $files,
		'create_time' => SYS_TIME
	));

	$contact_time = $_G['gp_next-contact-time'] ? strtotime($_G['gp_next-contact-time']) : 0;

	update('customer', $customer['id'], array(
		'last_contact_time' => SYS_TIME,
		'next_contact_time' => $contact_time
	));
	jsonp('操作成功');
}else if( $act == 'change_field' ){
	if( !$customer ){
		jsonp('网络繁忙', 'alert', 1);
	}
	$field = $_G['gp_field'];
	$data = $_G['gp_data'] ? $_G['gp_data'] : '';
	if( $field ){

		if( $field == 'name' && !$data ){
			jsonp('客户名称不能为空', 'alert', 1);
		}

		if( $field == 'province' ){
			if( $data != $customer['province'] ){
				$update['city'] = 0;
			}
		}

		if( $field == 'demands' ){
			$demands = array();
			delete('customer_demands', $customer['id'], 'customerid');
			foreach( $data as $k => $v ){
				DB::Insert('customer_demands', array(
					'customerid' => $customer['id'],
					'key' => $v
				));
				$demands[$v] = 1;
			}
			$data = json_encode($demands);
		}
		$update[$field] = $data;
		$update['update_time'] = SYS_TIME;

		update('customer', $customer['id'], $update);
		jsonp('操作成功', 'alert', 0);
	}
	jsonp('请求失败', 'alert', 1);
}else if( $act == 'upload_file' ){
	$state = dupload('file', 'customer', '', true);
	echo $state;
}else if( $act == 'delete_file' ){
	$file = urldecode($_G['gp_file']);
	$filepath = iconv('utf-8', 'gbk//IGNORE', trim(APP_PATH . $file));
	if( is_file ( $filepath ) ){
		unlink($filepath);
		jsonp('ok');
	}
	jsonp('error');
}